import React, { useEffect, useState } from "react";
import { get } from "../../util/get";
import { Table, Tag, Space, Button, message } from "antd";
import { ArrowUpOutlined,ArrowDownOutlined } from "@ant-design/icons"
import { post } from "../../util/post";
const { Column } = Table;
const User = () => {
    const token = localStorage.getItem('TOKEN')
    const [data, setData] = useState([])
    const [total, setTotal] = useState(0)
    const [page, setPage] = useState(1)
    const tagMap = new Map([['SUPER_ADMIN','#f50'],['ADMIN','#2db7f5'],['USER ','default']]) 
        const getUserList = async () => {
        const res = await get(`/user/user/list?page=${page}&limit=7`, token)
        const {msg,code,page:{list,totalCount}} = res.data
        if(!code)
          {
            setData(list)
            setTotal(totalCount)
          }
          else message.error(msg)
    }
    useEffect(() => {
        getUserList()
    }, [page])
    const handleUp =async (uid) => {
      const res = await post(`/user/userrole/${uid}/beAdmin`,{},token)
      const {code,msg} = res.data
      if(!code) {
        message.success(msg)
        getUserList()
      }
      else message.error(msg)
    }
    const handleDown = async (uid) => {
      const res = await post(`/user/userrole/${uid}/removeAdmin`,{},token)
      const {code,msg} = res.data
      if(!code) {
        message.success(msg)
        getUserList()
      }
      else message.error(msg)
    }
    return (
        <>
            <Table dataSource={data}
            pagination={{
              total,
              page,
              defaultPageSize:7,
              onChange:(page)=>{
                setPage(page)
              }
            }}>
                <Column title="用户名" dataIndex={"username"} key={"username"} />
                <Column title="角色" dataIndex={"roles"} key={"roles"} render={(i) => {
                    return <div>
                        {
                            i?i.map(item =><Tag color={tagMap.get(item.name)}>{`${item.name} ${item.description}`}</Tag>):""
                        }
                    </div>
                }} />
    
                <Column title="操作" dataIndex={"action"} key={"action"} render={(_, item) => {
                    return (
                        <Space>
                            <Button type="primary" onClick={() => handleUp(item.resourceId)} shape="circle" icon={<ArrowUpOutlined />} size={"large"} />
                            <Button type="primary" onClick={() => handleDown(item.resourceId)} danger shape="circle" icon={<ArrowDownOutlined />} size={"large"} />
                        </Space>
                    )
                }}>
                </Column>
            </Table>
        </>
    )
}
export default User;
